<?php

namespace app\common\model\xilumarket;

use app\admin\model\xilumarket\comments\TopicForumComment;
use app\common\model\Autoreplay;
use app\common\model\Config;
use app\common\model\DeliveryKey;
use think\Exception;
use think\Model;
use function fast\array_get;


class TopicForum extends Model
{

    

    

    // 表名
    protected $name = 'xilumarket_topic_forum';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [
        'status_text',
        'hot_status_text',
        'check_status_text',
        'createtime_text',
        'images_text'
    ];

    
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }

    public function getHotStatusList()
    {
        return ['0' => __('Hot_status 0'), '1' => __('Hot_status 1')];
    }

    public function getCheckStatusList()
    {
        return ['1' => __('Check_status 1'), '2' => __('Check_status 2'), '3' => __('Check_status 3')];
    }

    public function getImagesTextAttr($value,$data){
        $images = [];
        $value = isset($data['images'])?$data['images']:'';
        if($value && is_string($value)){
            $images_array = explode(',',$value);
            foreach ($images_array as $image){
                $images[] = cdnurl($image,true);
            }
        }
        return $images;
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getHotStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['hot_status']) ? $data['hot_status'] : '');
        $list = $this->getHotStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCheckStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['check_status']) ? $data['check_status'] : '');
        $list = $this->getCheckStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCreatetimeTextAttr($value,$data){
        if(isset($data['createtime'])){
            return xilumarket_time_cha(time(),$data['createtime']);
        }
        return '';
    }

    #发帖人信息
    public function user(){
        return $this->belongsTo('\app\common\model\User','user_id');
    }
    #话题
    public function topic(){
        return $this->belongsTo('Topic','topic_id');
    }

    #关注
    public function focus(){
        return $this->belongsTo('UserFocus','user_id','focus_user_id')->setEagerlyType(0);
    }

    #关注
    public function isFocus(){
        return $this->hasMany(UserFocus::class,'focus_user_id','user_id');
    }

    #点赞
    public function isFav(){
        return $this->hasMany(UserFavourite::class,'favourite_id','id');
    }

    #收藏
    public function isCollection(){
        return $this->hasMany(UserCollection::class,'collection_id','id');
    }

    public static function getCount($where){
        return self::where($where)->count();
    }

    /**
     * 添加帖子
     */
    public static function add($params,$user_id){

        $params['user_id'] = $user_id;


        if(isset($params['images'])){
            $params['images'] = is_array($params['images']) ? implode(',',$params['images']) : $params['images'];
        }

        $validate = new \app\common\validate\xilumarket\TopicForum;
        if(!$validate->check($params)){
            throw new Exception($validate->getError());
        }

        //判断是否需要审核
        $shopinfo = \app\common\model\xilumarket\Config::getMyConfig('shopinfo');
        if($shopinfo && $shopinfo['forum_check_switch'] == 0){
            $params['check_status'] = 2;
        }

        $result = self::create($params);
        $content = array_get($params, 'content');
        check_sens_word($content);
        if($content){
            $keys = Autoreplay::where(['type' => 'topic', 'user_id' => $user_id])->select();
            $replay = auto_replay($content, $keys->toArray(), 'key', false);
            if($replay) {
                $comment = new TopicForumComment();
                $comment->forum_id = $result->id;
                $comment->user_id = $user_id;
                $comment->content = $replay['replay'];
                $comment->status = 'normal';
                $comment->images = json_encode($replay['images']);
                $comment->save();
                $result->setInc('comment_count');
            }
        }
        if($params['topic_id']){
            $forumCount = TopicForum::where('topic_id', $params['topic_id'])->count();
            Topic::where('id', $params['topic_id'])->update(['forum_count' => $forumCount]);
        }
        return $result;
    }

    /**
     * 推荐帖子列表
     * @param $params
     * @param int|NULL $user_id
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function recmmendLists($params,$user_id=NULL){
        $query = self::with(['user'=>function($query){
            $query->withField(['id','nickname','avatar']);
        },
            'topic'=>function($query){
                $query->field(['id','name','image','description','forum_count']);
            }])
            ->field("id,user_id,content,topic_id,images,status,fav_count,comment_count,collection_count,createtime")
            ->where('status','normal')
            ->whereIn("check_status", ['2'])
            //->where('hot_status',1)
            ->order('fav_count desc,updatetime desc');
        //话题帖子
        $pagesize = array_get($params,'pagesize',10);
        $paginator = $query
            ->paginate($pagesize)
            ->each(function ($row) use($user_id){
                $row->relationCount($row,['isFocus'=>function($query) use($user_id){
                    $query->where('user_id',$user_id);
                },
                ]);
                $row->relationCount($row,['isFav'=>function($query) use($user_id){
                    $query->where('user_id',$user_id)->where('favourite_type',UserFavourite::TYPE_FORUM);
                }]);
                $row->relationCount($row,['isCollection'=>function($query) use($user_id){
                    $query->where('user_id',$user_id)->where('collection_type',UserCollection::TYPE_FORUM);
                }]);
            });
        return $paginator;
    }


    /**
     * 关注帖子列表
     * @param $params
     * @param bool $hot
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function focusLists($params,$user_id=NULL){
        $query = self::field("id,user_id,content,topic_id,images,status,fav_count,comment_count,collection_count,createtime")
            ->with(['user'=>function($query){
            $query->withField(['id','nickname','avatar']);
        },
            'focus',
            'topic'=>function($query){
                $query->field(['id','name','image','description','forum_count']);
            }])
            ->where(['focus.user_id'=>$user_id])
            ->where('topic_forum.status','normal')
            ->whereIn("topic_forum.check_status", ['2'])
            ->order('focus.createtime','desc');

        $pagesize = array_get($params,'pagesize',10);
        $paginator = $query
            ->paginate($pagesize)
            ->each(function ($row) use($user_id){
                $row->relationCount($row,['isFocus'=>function($query) use($user_id){
                    $query->where('user_id',$user_id);
                },
                ]);
                $row->relationCount($row,['isFav'=>function($query) use($user_id){
                    $query->where('user_id',$user_id)->where('favourite_type',UserFavourite::TYPE_FORUM);
                }]);
                $row->relationCount($row,['isCollection'=>function($query) use($user_id){
                    $query->where('user_id',$user_id)->where('collection_type',UserCollection::TYPE_FORUM);
                }]);
            });
        return $paginator;
    }

    /**
     * 帖子列表
     * @param $params
     * @param bool $hot
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function lists($params,$user_id=NULL){

        $query = self::with(['user'=>function($query){
            $query->withField(['id','nickname','avatar']);
        },
            'topic'=>function($query){
            $query->field(['id','name','image','description','forum_count']);
        }])
            ->field("id,user_id,content,topic_id,images,status,fav_count,comment_count,collection_count,createtime")
            ->where('status','normal')
            ->whereIn("check_status", ['2']);
        $tab = array_get($params,'tab',-1);
        if($tab>=0){
            if($tab == 0){
                $query->where('hot_status',1)->order("fav_count desc");
            }else if($tab == 1){
                $query->order('createtime','desc');
            }else{
                $query->order('fav_count desc,updatetime desc');
            }
        }else{
            $query->order('updatetime','desc');
        }
        //话题帖子
        if($topic_id = array_get($params,'topic_id')){
            $query->where('topic_id',$topic_id);
        }
        $pagesize = array_get($params,'pagesize',10);
        $paginator = $query
            ->paginate($pagesize)
            ->each(function ($row) use($user_id){
                $row->relationCount($row,['isFocus'=>function($query) use($user_id){
                    $query->where('user_id',$user_id);
                },
                ]);
                $row->relationCount($row,['isFav'=>function($query) use($user_id){
                    $query->where('user_id',$user_id)->where('favourite_type',UserFavourite::TYPE_FORUM);
                }]);
                $row->relationCount($row,['isCollection'=>function($query) use($user_id){
                    $query->where('user_id',$user_id)->where('collection_type',UserCollection::TYPE_FORUM);
                }]);
            });
        return $paginator;
    }

    /**
     * 主页帖子列表
     * @param $params
     * @param bool $hot
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function homeLists($params,$user_id=NULL,$my_user_id=NULL){

        $query = self::with(['user'=>function($query){
            $query->withField(['id','nickname','avatar']);
        },
            'topic'=>function($query){
                $query->field(['id','name','image','description','forum_count']);
            }])
            ->field("id,user_id,content,topic_id,images,status,fav_count,comment_count,collection_count,createtime")
            ->where('user_id',$user_id)
            ->where('status','normal');
        $pagesize = array_get($params,'pagesize',10);
        $paginator = $query
            ->paginate($pagesize)
            ->each(function ($row) use($user_id,$my_user_id){
                $row->relationCount($row,['isFocus'=>function($query) use($user_id){
                    $query->where('user_id',$user_id);
                },
                ]);
                $row->relationCount($row,['isFav'=>function($query) use($user_id){
                    $query->where('user_id',$user_id)->where('favourite_type',UserFavourite::TYPE_FORUM);
                }]);
                $row->relationCount($row,['isCollection'=>function($query) use($user_id){
                    $query->where('user_id',$user_id)->where('collection_type',UserCollection::TYPE_FORUM);
                }]);
                $row->setAttr('show_focus' ,$user_id == $my_user_id ? false :true);
            });
        return $paginator;
    }


    public static function delForum($params,$user_id){
        if(!$forum_id = array_get($params,'forum_id')){
            throw new Exception("删除成功");
        }
        $row = self::get($forum_id);
        if(!$row){
            throw new Exception("帖子不存在");
        }
        if($row->user_id != $user_id){
            throw new Exception("无权操作");
        }
        $row->delete();
        return true;
    }

    /**
     * 帖子详情
     */
    public static function detail($forum_id,$user_id){
        $row = static::field("id,user_id,content,topic_id,images,status,fav_count,comment_count,collection_count,createtime")->where('id',$forum_id)
            ->with(['user'=>function($query){
            $query->withField(['id','nickname','avatar']);
        },'topic'=>function($query){
            $query->withField(['id','name']);
        }])->find();
        if($row){
            #关注
            $row->relationCount($row,['isFocus'=>function($query) use($user_id){
                $query->where('user_id',$user_id);
            }]);
            #点赞
            $row->relationCount($row,['isFav'=>function($query) use($user_id){
                $query->where('user_id',$user_id)->where('favourite_type',UserFavourite::TYPE_FORUM);
            }]);
            #收藏
            $row->relationCount($row,['isCollection'=>function($query) use($user_id){
                $query->where('user_id',$user_id)->where('collection_type',UserCollection::TYPE_FORUM);
            }]);
        }
        return $row;
    }

}
